//
//  AppDelegate.m
//  Test
//
//  Created by jansh on 16/1/12.
//  Copyright © 2016年 jansh. All rights reserved.
//

#import "AppDelegate.h"
#import "ViewController.h"
//#import <FBAllocationTracker/FBAllocationTracker.h>

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
//    NSLog(@"1111");
//   NSDictionary *tmpDic = [[NSBundle mainBundle] infoDictionary];
//    NSString *currentVersion = [tmpDic objectForKey:@"CFBundleShortVersionString"];
//    NSLog(@"%@", currentVersion);
    
//    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
//    self.window.backgroundColor = [UIColor whiteColor];
//    ViewController *rootVC = [[ViewController alloc] init];
//    self.window.rootViewController = rootVC;
    
    // 取消所有的通知
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    
//    [self.window makeKeyAndVisible];
//    
//    if ([[UIApplication sharedApplication] currentUserNotificationSettings].types != UIUserNotificationTypeNone) {
//        [self addLocalNotification];
//    } else {
//        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil]];
//    }
    
    return YES;
}

- (void)addLocalNotification
{
    UILocalNotification *location = [[UILocalNotification alloc] init];
    NSLog(@"nsdate = %@", [NSDate dateWithTimeIntervalSinceNow:60*60*8]);
    location.fireDate = [NSDate dateWithTimeIntervalSinceNow:10];
//    location.timeZone = [NSTimeZone localTimeZone];
    location.repeatInterval = 2;
    location.alertBody = @"这是本地通知";
    location.alertAction = @"这是本地通知 Action";
    location.alertTitle = @"hello";
    location.alertLaunchImage = @"fox.png";
    location.applicationIconBadgeNumber = 1;
    
    // 调用通知
    [[UIApplication sharedApplication] scheduleLocalNotification:location];
}

- (void)judgeCurrentVersionWithAppStore
{
    __weak typeof(self) mySelf = self;
    NSString *tmpString = @"https://itunes.apple.com/lookup?id=1060016323";
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:tmpString]];
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration ephemeralSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSDictionary *tmpDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
        NSArray *tmpArray = [tmpDic objectForKey:@"results"];
        NSString *appString = [[tmpArray lastObject] objectForKey:@"version"];
        NSLog(@"%@", appString);
        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"商店有新版本可以更新了" preferredStyle:(UIAlertControllerStyleAlert)];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"%@",[[tmpArray lastObject] objectForKey:@"trackViewUrl"]);
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[[tmpArray lastObject] objectForKey:@"trackViewUrl"]]];
                });
                
//                dispatch_after(0.2, dispatch_get_main_queue(), ^{
//                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[[tmpArray lastObject] objectForKey:@"trackViewUrl"]]];
//                });
                
            }];
            UIAlertAction *actionA = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
            [alertVC addAction:action];
            [alertVC addAction:actionA];
            [mySelf.window.rootViewController presentViewController:alertVC animated:YES completion:nil];
        });
    }];
    [dataTask resume];
}

//- (void)applicationDidFinishLaunching:(UIApplication *)application
//{
//    NSLog(@"2222");
//}

- (BOOL)application:(UIApplication *)application willFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//    [self judgeCurrentVersionWithAppStore];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0]; // 进入前台取消应用图标信息
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    if (notificationSettings.types != UIUserNotificationTypeNone) {
        [self addLocalNotification];
    }
}

@end
